package com.youxin.third.auth.config.interceptors;

import com.alibaba.fastjson.JSONObject;
import com.youxin.base.BaseResultCode;
import com.youxin.base.TResult;
import com.youxin.exception.SystemException;
import com.youxin.third.auth.context.PlatformContextHandler;
import com.youxin.third.auth.model.AccessToken;
import com.youxin.third.auth.model.ClientDetails;
import com.youxin.third.auth.service.manager.OAuthManager;
import org.apache.oltu.oauth2.common.OAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * description: ResourceInterceptor <br>
 * date: 2020/3/8 11:43 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Component
public class PlatformInterceptor extends HandlerInterceptorAdapter {

    private static final Logger log = LoggerFactory.getLogger(PlatformInterceptor.class);

    @Resource
    private OAuthManager oAuthManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            final String accessToken = request.getParameter(OAuth.OAUTH_ACCESS_TOKEN);
            AccessToken aToken = oAuthManager.findAccessTokenByTokenId(accessToken);
            validateToken(accessToken, aToken);

            //Validate client details by resource-id
            final ClientDetails clientDetails = oAuthManager.findClientDetails(aToken.getClientId());
            validateClientDetails(accessToken, aToken, clientDetails);
            PlatformContextHandler.setAccessToken(accessToken);
            PlatformContextHandler.setClientId(aToken.getClientId());
            PlatformContextHandler.setUserName(aToken.getUsername());
        } catch (SystemException e) {
            log.warn("解析token信息时，发生异常. ", e);
            returnJson(response,e);
            return false;
        }
        return super.preHandle(request, response, handler);
    }

    private void validateToken(String token, AccessToken accessToken)  {
        if (accessToken == null) {
            log.debug("Invalid access_token: {}, because it is null", token);
            throw new SystemException(BaseResultCode.COMMON_FAIL,"access_token有误");
        }
        if (accessToken.tokenExpired()) {
            log.debug("Invalid access_token: {}, because it is expired", token);
            throw new SystemException(BaseResultCode.COMMON_FAIL,"access_token有误");

        }
    }

    private void validateClientDetails(String token, AccessToken accessToken, ClientDetails clientDetails) {
        if (clientDetails == null || clientDetails.getArchived() == 1) {
            log.debug("Invalid ClientDetails: {} by client_id: {}, it is null or archived", clientDetails, accessToken.getClientId());
            throw new SystemException(BaseResultCode.COMMON_FAIL,"client_id有误");

        }
    }

    private void returnJson(HttpServletResponse response,SystemException se){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        try {
            writer = response.getWriter();
            TResult result =TResult.build(se.getCode(),se.getMsg());
            writer.print(JSONObject.toJSONString(result));
        } catch (IOException e){
            log.error("拉截器异常",e);
        } finally {
            if(writer != null){
                writer.close();
            }
        }
    }

}
